//
//  SchemeViewController.m
//  liangyi
//
//  Created by 张水 on 17/1/12.
//  Copyright © 2017年 yswh. All rights reserved.
//

#import "SchemeViewController.h"
#import "SchemeCell.h"
#import "SchemeModel.h"
#import "ImageViewCell.h"
#import "ZXVideo.h"
#import "VideoPlayViewController.h"
#import "DetailVideoViewController.h"
#import "SchemeheadView.h"
#import "LoginViewController.h"
#import "RegisteredViewController.h"


@interface SchemeViewController () <UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong) NSMutableArray *dataArr;

@property(nonatomic,strong) NSMutableArray *collViewArr;

@property(nonatomic,strong) NSMutableArray *stageArr;

@property(nonatomic,strong) UITableView *tableView;

@property(nonatomic,strong) SchemeheadView *headView;

@property(nonatomic,strong) UIView  *backView;

@property(nonatomic,strong) UIAlertView *alretView1;

@property(nonatomic,strong) UIAlertView *alretView2;

@property(nonatomic,strong) GFCalendarView *calendar;

@property(nonatomic,copy)NSString *sid;

@property(nonatomic,copy)NSString *pid;

@property(nonatomic,copy)NSString *backtime;

@property(nonatomic,copy)NSString *operationTime;

@end


@implementation SchemeViewController

static NSString *SchemeCellID = @"SchemeCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"方案详情";
    self.view.backgroundColor = [UIColor whiteColor];
    self.dataArr = [NSMutableArray array];
    self.collViewArr = [NSMutableArray array];
    self.stageArr = [NSMutableArray array];
//    [self setupNavigation];
    [self initUI];
    
    
}
-(void)setupNavigation{
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 100, 25);
    [rightButton setTitle:@"修改方案" forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [rightButton addTarget:self action:@selector(showrightAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightButton];
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getschemeData];
    [self getMyschemeDesData];
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
-(void)setModel:(RightModel *)model{
    _model = model;
    self.sid = model.id;
}
-(void)initUI {
    
    self.headView = [[SchemeheadView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 270)];
    [self.headView.BeginTrain addTarget:self action:@selector(beginTrainAction) forControlEvents:UIControlEventTouchUpInside];
    [self.headView.ModeiScheme addTarget:self action:@selector(SchemeModeiTimeAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollEnabled = YES;
    [CommonMethod hiddleExtendCellFromTableview:_tableView];
    self.tableView.tableHeaderView = self.headView;
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[SchemeCell class] forCellReuseIdentifier:SchemeCellID];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    
    self.backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    self.backView.backgroundColor = [UIColor blackColor];
    self.backView.alpha = 0.4;
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removeSubViews)];
    [self.backView addGestureRecognizer:tapGesture];
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.collViewArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SchemeCell *cell = [tableView dequeueReusableCellWithIdentifier:SchemeCellID forIndexPath:indexPath];
    if (!cell) {
        cell = [cell initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:SchemeCellID];
    }
    
    cell.model = self.collViewArr[indexPath.row];

    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 180;
}

-(void)beginTrainAction{
    

    NSString *userLogin = [CommonMethod fuckNULL:[UserDefaultsUtlis getValueForKey:@"userid"]];
    if (userLogin.length == 0) {
        self.alretView2 = [[UIAlertView alloc]initWithTitle:@"请登录后查看!!!" message:nil delegate: self cancelButtonTitle:@"注册" otherButtonTitles:@"登录", nil];
        [self.alretView2 show];
        
        return;
    }
    if (self.stageArr.count == 0){
        [self creatMyScheme];
        return ;
    }
}
-(void)creatMyScheme{
    [self.view addSubview:self.backView];
    
    CGFloat width = self.view.bounds.size.width - 20;
    CGPoint origin = CGPointMake(10.0, 64.0 + 70);
    
    self.calendar = [[GFCalendarView alloc] initWithFrameOrigin:origin width:width];
    _calendar.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_calendar];
    __weak SchemeViewController *weakSelf = self;
    // 点击时间的回调
    _calendar.didSelectDayHandler = ^(NSInteger year, NSInteger month, NSInteger day) {
        
        weakSelf.operationTime = [NSString stringWithFormat:@"%ld-%ld-%ld",(long)year,(long)month,(long)day];
        [weakSelf subimitBtnDidClick];
        [weakSelf.calendar removeFromSuperview];
        [weakSelf.backView removeFromSuperview];
    };
}

-(void)removeSubViews{
    [self.calendar removeFromSuperview];
    [self.backView removeFromSuperview];
}

-(void)subimitBtnDidClick{
    
    NSString *url = [BASEURL stringByAppendingString:kURL_Plan];
    NSDictionary *dict = @{@"schemeId":self.sid,
                           @"operationTime":self.operationTime};
    NSLog(@"%@",dict);
    NSString *jsonString = [NSString dictionaryToJson:dict];
    NSString *AESString = [NSString AES128Encrypt:jsonString];
    NSDictionary *parameters = @{@"parameters":AESString,
                                 @"login":[NSString AES128Encrypt:[NSString stringWithFormat:@"%@@@%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"userid"],ApplicationDelegate.deviceID]]};
    
    [AppNetwork requestWithPath:url parameters:parameters success:^(id responseObject) {
        NSLog(@"%@",responseObject);
        NetworkModel *network = [NetworkModel mj_objectWithKeyValues:responseObject];
        NSInteger code = network.code.integerValue;
        if (code == 0){
            [self getMyschemeDesData];
        }else {
            [CustomProgressHUD showErrorWithStatus:network.errorDescription];
        }
    } failure:^(id error) {
        [CustomProgressHUD showErrorWithStatus:k_NetWorkStatus_Error];
    }];
}

-(void)SchemeModeiTimeAction{
    
    NSString *userLogin = [CommonMethod fuckNULL:[UserDefaultsUtlis getValueForKey:@"userid"]];
    if (userLogin.length == 0) {
        LoginViewController *vc = [LoginViewController new];
        UINavigationController *navVc = [[UINavigationController alloc]initWithRootViewController:vc];
        [self presentViewController:navVc animated:YES completion:nil];
        return ;
    }
    
    
    if (self.stageArr.count == 0){
        [CustomProgressHUD showSuccessWithStatus:@"您还没有定制方案"];
        return ;
    }
    
    self.alretView1 = [[UIAlertView alloc]initWithTitle:@"确定修改方案么?" message:@"请您严格按照医师的指导执行您的训练计划，如若随意修改，可能会出现一些问题，请您慎重选择。" delegate: self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [self.alretView1 show];
    
}


-(void)getschemeData{
    NSString *url = [BASEURL stringByAppendingString:kURL_Stage];
    NSDictionary *dict = @{@"sid":self.sid};
    NSLog(@"%@",dict);
    NSString *jsonString = [NSString dictionaryToJson:dict];
    NSString *AESString = [NSString AES128Encrypt:jsonString];
    NSDictionary *parameters = @{@"parameters":AESString};
    [AppNetwork requestWithPath:url parameters:parameters success:^(id responseObject) {
        NetworkModel *network = [NetworkModel mj_objectWithKeyValues:responseObject];
        NSInteger code = network.code.integerValue;
        NSLog(@"%@",network.dataObject);
        if (code == 0){
             NSArray *arr = [StageModel mj_objectArrayWithKeyValuesArray:network.dataObject];
            [self.collViewArr removeAllObjects];
            self.collViewArr = [StageModel mj_objectArrayWithKeyValuesArray:arr];
            NSLog(@"%lu",(unsigned long)self.collViewArr.count);
            [self.tableView reloadData];
        }else{
            [CustomProgressHUD showErrorWithStatus:network.errorDescription];
        }
    } failure:^(id error) {
        [CustomProgressHUD showErrorWithStatus:k_NetWorkStatus_Error];
    }];
    
}
-(void)getMyschemeDesData{
    NSString *url = [BASEURL stringByAppendingString:kURL_MyPlain];
    NSDictionary *dict = @{@"login":[NSString  AES128Encrypt:[NSString stringWithFormat:@"%@@@%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"userid"],ApplicationDelegate.deviceID]]};
    [AppNetwork requestWithPath:url parameters:dict success:^(id responseObject) {
        NetworkModel *network = [NetworkModel mj_objectWithKeyValues:responseObject];
        NSLog(@"%@",network.dataObject);
        NSInteger code = network.code.integerValue;
        if (code == 0){
            SchemeModel *allData = [SchemeModel mj_objectWithKeyValues:network.dataObject];
            [self.stageArr removeAllObjects];
            [self.stageArr addObjectsFromArray:allData.stageList];
            self.stageArr =  [MyschemeModel mj_objectArrayWithKeyValuesArray:self.stageArr];

            PlanModel *model = [PlanModel mj_objectWithKeyValues:allData.plan];
            self.pid = model.id;
            self.backtime = [NSString timeWithTimeIntervalString:model.operationTime];
            NSLog(@"%@",self.backtime);
            [self.headView.ModeiTime setTitle:[NSString stringWithFormat:@"(手术时间:%@)",self.backtime] forState:UIControlStateNormal];
            StageModel *stage = [StageModel mj_objectWithKeyValues:allData.stage];
            if (stage != nil){
                [self.headView loadMySchemeData:stage];
            }else{
                self.headView.sectionName.hidden = YES;
                self.headView.sectionDes.hidden = YES;
                self.headView.desLable.text = @"当前阶段没有训练内容,请您休息一下吧!";
            }
            
            [self.dataArr removeAllObjects];
            [self.dataArr addObjectsFromArray:stage.recoveries];
            self.dataArr = [recoveriesModel mj_objectArrayWithKeyValuesArray:self.dataArr];
            self.headView.BeginTrain.hidden = YES;
        }else{
             self.headView.desLable.text = @"您还没有选择你的训练计划,请点击下面开始训练按钮,选择您的训练计划吧!";
             self.headView.modityTime.hidden = YES;
//             self.headView.ModeiScheme.hidden = YES;
        }
    } failure:^(id error) {
        [CustomProgressHUD showErrorWithStatus:k_NetWorkStatus_Error];
    }];
    
}
-(void)showrightAction{
    
    NSString *userLogin = [CommonMethod fuckNULL:[UserDefaultsUtlis getValueForKey:@"userid"]];
    if (userLogin.length == 0) {
        self.alretView2 = [[UIAlertView alloc]initWithTitle:@"请登录后进行修改!!!" message:nil delegate: self cancelButtonTitle:@"注册" otherButtonTitles:@"登录", nil];
        [self.alretView2 show];
        
        return;
    }
    
    
    if (self.stageArr.count == 0){
        [CustomProgressHUD showSuccessWithStatus:@"您还没有定制方案"];
        return ;
    }
    
    self.alretView1 = [[UIAlertView alloc]initWithTitle:@"确定修改方案么?" message:@"请您严格按照医师的指导执行您的训练计划，如若随意修改，可能会出现一些问题，请您慎重选择。" delegate: self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [self.alretView1 show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (alertView == self.alretView1){
    
    if (buttonIndex == 0){

    }
    if (buttonIndex == 1){
        
        NSString *url = [BASEURL stringByAppendingString:kURL_delScheme];
        NSDictionary *dict = @{@"pid":self.pid};
        NSLog(@"%@",dict);
        NSString *jsonString = [NSString dictionaryToJson:dict];
        NSString *AESString = [NSString AES128Encrypt:jsonString];
        NSDictionary *parameters = @{@"parameters":AESString,
                                     @"login":[NSString  AES128Encrypt:[NSString stringWithFormat:@"%@@@%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"userid"],ApplicationDelegate.deviceID]]};
        [AppNetwork requestWithPath:url parameters:parameters success:^(id responseObject) {
            NetworkModel *network = [NetworkModel mj_objectWithKeyValues:responseObject];
            NSInteger code = network.code.integerValue;
            if (code == 0){
                [self.navigationController popToRootViewControllerAnimated:YES];
            }else{
                [CustomProgressHUD showErrorWithStatus:network.errorDescription];
            }
        } failure:^(id error) {
            [CustomProgressHUD showErrorWithStatus:k_NetWorkStatus_Error];
        }];
        
    }
    }else{
        
        if (buttonIndex == 0){
            RegisteredViewController *vc = [RegisteredViewController new];
            UINavigationController *navVC = [[UINavigationController alloc]initWithRootViewController:vc];
            [self presentViewController:navVC animated:YES completion:nil];
        }
        if (buttonIndex == 1){
            LoginViewController *vc = [LoginViewController new];
            UINavigationController *navVc = [[UINavigationController alloc]initWithRootViewController:vc];
            [self presentViewController:navVc animated:YES completion:nil];
        }
        
    }
}



@end
